package com.aoxiang.zbox.common;

import com.aoxiang.zbox.model.dto.SimpleUser;

import java.util.HashMap;
import java.util.Map;

public class UserContextHolder {
    private static ThreadLocal<Map<String, Object>> applicationContextThreadLocal = new ThreadLocal<>();

    public static SimpleUser getUser() {
        return (SimpleUser) applicationContextThreadLocal.get().get("user");
    }

    public static void setUser(SimpleUser user) {
        Map<String, Object> applicationContext = applicationContextThreadLocal.get();
        if (applicationContext == null) {
            applicationContext = new HashMap<>();
        }
        applicationContext.put("user", user);
        applicationContextThreadLocal.set(applicationContext);
    }

    public static void userClear() {
        Map<String, Object> applicationContext = applicationContextThreadLocal.get();
        if (applicationContext == null) {
            applicationContext = new HashMap<>();
        }
        applicationContext.put("user", null);
        applicationContextThreadLocal.set(applicationContext);
    }

    // 清除当前线程的 userId
    public static void clear() {
        applicationContextThreadLocal.remove();
    }
}
